from model.message_model import Message
from database_connection.index import Session
from utils.utils import add_model

session = Session()

def add_one_message(msg_info):
    try:
        msg = add_model(msg_info, "message")
        session.add(msg)
        session.commit()
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
        # 将错误信息返回给前端
    else:
        session.commit()
        session.flush()
        session.refresh(msg)
        return {"msg": "success", "data": msg}


def pagination_query(page_number,page_size):
    # page_size每页显示的条数
    # page_number当前是第几页
    # 计算偏移量
    offset = (page_number - 1) * page_size
    try:
        msg_list = session.query(Message).limit(page_size).offset(offset).all()
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
        # 将错误信息返回给前端
    else:
        return {"msg": "success", "data": msg_list}

def find_count():
    try:
        count = session.query(Message).count()
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
        # 将错误信息返回给前端
    else:
        return {"msg": "success", "data": count}

